package Test07_09;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 14229 on 2020/2/21.
 */
public class Test {
    public static void main(String[] args) throws IOException {
        Test t = new Test();
        t.addGoods(null,"A类","介绍");

        List<Goods> goodsList = t.getGoodsList();
        for (Goods goods : goodsList) {
            System.out.println(goods);
        }

        Map<String, String> goodsList3 = t.getGoodsList3("20200221110009113966");
        for (Map.Entry<String, String> entry : goodsList3.entrySet()) {
            System.out.println(entry.getKey()+"  "+entry.getValue());
        }


    }
    public Map<String,String> getGoodsList3 (String id) throws IOException {
        Map<String,String> map = new HashMap<>();
        List<Goods> goodsList = getGoodsList();
        for (Goods goods : goodsList) {
            if (goods.getId().equalsIgnoreCase(id)){
                map.put("id",goods.getId());
                map.put("goodName",goods.getGoodName());
                map.put("goodsInfo",goods.getGoodsInfo());
                return map;
            }
        }
        System.out.println("id错误");
        return map;
    }


    public List<Goods>  getGoodsList () throws IOException {
        List<Goods> list = new ArrayList<>();
        List<String> lines = FileUtils.readLines(new File("goods_info.txt"), "UTF-8");
        for (String line : lines) {
            String[] split = line.split(" ");
            list.add(new Goods(split[0],split[1],split[2]));
        }
        return list;
    }

    public void addGoods(String id, String  goodName, String  goodsInfo) throws IOException {
        File f = new File("goods_info.txt");
        f.createNewFile();
        Date da = new Date();
        SimpleDateFormat si = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String format = si.format(da);
        Random ra = new Random();
        int i = ra.nextInt(900)+100;
        id = format+""+i;

        List<String> lines = FileUtils.readLines(f, "UTF-8");
        if (lines.size()==0){
            String a = "";
            a =id+" "+goodName+" "+goodsInfo;
            FileUtils.writeStringToFile(f,a,true);
        }else {
            for (String line : lines) {
                String[] split = line.split(" ");
                if (split[0].equalsIgnoreCase(id)){
                    System.out.println("系统自动生成的ID重复，请重新注册");
                    return;
                }
            }
            String a = "";
            a ="\n"+id+" "+goodName+" "+goodsInfo;
            FileUtils.writeStringToFile(f,a,true);
        }

    }
}
